<template>
  <div class="chart-container">
    <div class="chart-header">
      <h3>图书分类统计</h3>
    </div>
    <div ref="chartRef" class="chart-content"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import { getCategoryStats } from '@/api/statistics'

const props = defineProps({
  timeRange: {
    type: Array,
    default: () => []
  }
})

const chartRef = ref(null)
let chart = null

const initChart = async () => {
  await nextTick()
  if (!chartRef.value) return
  
  if (chart) {
    chart.dispose()
  }
  
  chart = echarts.init(chartRef.value)
  await updateChart()
}

const updateChart = async () => {
  if (!chart) return
  
  try {
    const params = {}
    if (props.timeRange && props.timeRange.length === 2) {
      params.startDate = props.timeRange[0]
      params.endDate = props.timeRange[1]
    }
    
    const response = await getCategoryStats(params)
    if (response.code === 0 && response.data) {
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center'
        },
        series: [
          {
            name: '图书分类',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c} ({d}%)'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: response.data
          }
        ]
      }
      chart.setOption(option)
    }
  } catch (error) {
    console.error('更新图表失败:', error)
  }
}

// 监听父组件传递的 timeRange 变化
watch(() => props.timeRange, () => {
  updateChart()
}, { deep: true })

const handleResize = () => {
  chart?.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-content {
  width: 100%;
  height: calc(100% - 60px);
}
</style> 